package com.wen.springbootorderserver.dao;

import com.wen.springbootorderserver.pojo.Orders;
import com.wen.springbootorderserver.util.JsonUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class OrderMqService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostConstruct
    public void regCallback(){
        System.err.println("+++++++++++++++++++++++++++++++++++");
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.err.println("======================================");
                System.out.println("cause:"+cause);
                //如果ack为true代表消息已经收到
                String orderId = correlationData.getId();
                if(!ack){
                    //这里可能要进行其他方式进行存储
                    System.out.println("MQ队列应答失败，orderId是："+orderId);
                    return;
                }
                try{
                    String sql = "update order_message set status = 1 where order_id = ?";
                    int update = jdbcTemplate.update(sql, orderId);
                    if(update == 1){
                        System.out.println("本地消息状态修改成功，成功投递消息到队列中");
                    }
                }catch (Exception e){
                    System.out.println("本地状态修改失败，出现异常："+ e.getMessage());
                }
            }
        });
    }



    public void sengMessage(Orders order){
        System.err.println("-----------------------------");
        rabbitTemplate.convertAndSend("order_fanout_exchange","", JsonUtils.objectToJson(order),new CorrelationData(order.getOrderId()));
    }

}
